﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using _DataProvider;
using ServiceConsumer;

public partial class Admin_Parts_XemCTGD : System.Web.UI.UserControl
{
    private SqlConnection connSql;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = loaddb();
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

    }

    public DataTable loaddb()
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        SqlDataAdapter daDepart = null;
        daDepart = new SqlDataAdapter("Select * from CTGiaoDich where TransID= '" + Request.Params["TransID"] + "'", connSql);
        DataSet ds = new DataSet();
        daDepart.Fill(ds);
        return ds.Tables[0];
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

        DataTable dt = loaddb();
        GridView1.EditIndex = e.NewEditIndex;
        //GridView1.DataBind();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

        DataTable dt = loaddb();
        GridView1.EditIndex = -1;
        GridView1.DataSource = dt;

        GridView1.DataBind();
    }

    public void UpdateState(int State)
    {
        try
        {

            DataProvider dt = new DataProvider();
            connSql = dt.connect();
            String sql = "Update CTGiaoDich set [State]=" + State + " where TransID = '" + Request.Params["TransID"] + "'";
            dt.executeNonQuery(sql);
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex + "')</script>");
        }

    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {


        //Update the values.
        GridViewRow row = GridView1.Rows[e.RowIndex];

        //dt.Rows[row.DataItemIndex]["ProductID"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
        DropDownList ddlPbx = (DropDownList)(GridView1.Rows[GridView1.EditIndex].FindControl("drl"));
        int State = int.Parse(ddlPbx.SelectedItem.Value);
        //((DropDownList)(row.Cells[10].Controls[0])).DataValueField;
        String kq = "";
        UpdateState(State);
        //String TransID = row.Cells[1].ToString();
        //String SID = row.Cells[2].ToString();
        if (ddlPbx.SelectedItem.Value == "1")
        {
            
            //DataRow dr = GetMoiGioi();
            //object result1 = WSProxy.CallWebService(dr["LinkWS"].ToString(), "WSLogin", new object[] { dr["UserName"].ToString(), dr["PassWord"].ToString() }); 

            //object result1 = ws.Product(str);
            //result1 = ChangeType(result1, "String");
            //Session["SIDMoiGioi"] = result1.ToString();
            String Credit = GetCreditNCC(row.Cells[1].Text);//dr["NameWS"].ToString()
            DataRow drprovi = GetProvider(row.Cells[1].Text);
            //object result2 = WSProxy.CallWebService(dr["LinkWS"].ToString(), "TraferMoneyForProvider", new object[] { result1.ToString(), Credit, float.Parse(row.Cells[8].Text), drprovi["SecureNumber"].ToString(), drprovi["CardHolder"].ToString() });
            BrokerServices broker = new BrokerServices();
            object result2 = broker.TranferMoneyForProvider(Credit, float.Parse(row.Cells[8].Text), drprovi["SecureNumber"].ToString(), drprovi["CardHolder"].ToString());
            result2 = ChangeType(result2, "String");
            if(result2.ToString() == "0")
            {
                
                Response.Write("<script>alert('Chuyển khoản thành công')</script>");
                int ProductID = GetProductIDFromTransId(row.Cells[1].Text, row.Cells[2].Text);
                UpdateStateProduct(ProductID, int.Parse(row.Cells[5].Text));
                kq = "0";

            }
            else
            {
                Response.Write("<script>alert('Chuyển khoản thất bại')</script>");
                kq = "-1";
            }
            DataRow drpro = GetProvider(row.Cells[1].Text);
            object resultlogin = WSProxy.CallWebService(drpro["LinkWS"].ToString(), "Service", "WSLogin", new object[] { drpro["PartnerID"].ToString(), drpro["PartnerPwd"].ToString() });
            resultlogin = ChangeType(resultlogin, "String");

            object resultwsx5 = WSProxy.CallWebService(drpro["LinkWS"].ToString(), "Service", "EndUpdateInventory", new object[] { resultlogin.ToString(), row.Cells[1].Text, kq });
            resultwsx5 = ChangeType(resultwsx5, "String");
            if (resultwsx5.ToString().Trim() == "0")
            {
                Response.Write("<script>alert('Đã gửi thông báo đến nhà cung cấp')</script>");
            }
            else
            {
                Response.Write("<script>alert('Không thể gửi thông báo đến nhà cung cấp')</script>");
            }
        }

       
        DataTable dt = loaddb();
        //Reset the edit index.
        GridView1.EditIndex = -1;
        GridView1.DataSource = dt;

        GridView1.DataBind();

    }
    public object ChangeType(object ob, String str)
    {
        if (str == "String")
            ob = Convert.ChangeType(ob, typeof(String));
        if (str == "Int")
            ob = Convert.ChangeType(ob, typeof(Int32));
        if (str == "Boolean")
            ob = Convert.ChangeType(ob, typeof(Boolean));
        if (str == "Float")
            ob = Convert.ChangeType(ob, typeof(float));
        if (str == "Data")
            ob = Convert.ChangeType(ob, typeof(DataTable));
        return ob;
    }

    public DataRow GetMoiGioi()
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        SqlDataAdapter Da = null;
        Da  = new SqlDataAdapter("Select * from NhaMoiGioi where DefaultBroker = 1",connSql);
        DataSet ds = new DataSet();
        Da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];
        return dr;
    }



    public String GetCreditNCC(String TransID)
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();

        String query = "Select ProviderID from SanPhamHopTac where TransID = '" + TransID + "'";
        String ProviderID = (String)dt.executeScalar(query);
        String query2 = "Select CreditCardNumber from NhaCungCap where ProviderID = '" + ProviderID + "'";
        String Credit = (String)dt.executeScalar(query2);
        
        return Credit;
    }

    public DataRow GetProvider(String TransID)
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        SqlDataAdapter da = null;
        da = new SqlDataAdapter("Select * from SanPhamHopTac,NhaCungCap where SanPhamHopTac.ProviderID = NhaCungCap.ProviderID and TransID = '" + TransID + "'",connSql);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];

        return dr;
    }


    public void UpdateStateProduct(int ProductID,int ProductQuantity)
    {
        try
        {
            _DataProvider.DataProvider dt = new _DataProvider.DataProvider();
            String query = "Update TaiLieu "
            + "Set State = 1,ProductQuantity = "+ProductQuantity+" where ProductId=" + ProductID + "";

            connSql = dt.connect();
            dt.executeNonQuery(query);

        }
        catch
        {


        }
    }


    public int GetProductIDFromTransId(String TransID, String SessionID)
    {
        //DataProvider dt = new DataProvider();
        //connSql = dt.connect();
        //SqlDataAdapter daDepart = null;
        //daDepart = new SqlDataAdapter("SELECT ProducID "
        //+ " FROM GiaoDich where TransID ='" + TransID + "'", connSql);
        //DataSet ds = new DataSet();
        //daDepart.Fill(ds);
        //if (ds.Tables[0].Rows.Count == 0)
        //{

        //    return kq;
        //}
        //DataRow dr = ds.Tables[0].Rows[0];
        //return dr["ProviderID"].ToString();
        try
        {
            _DataProvider.DataProvider dt = new _DataProvider.DataProvider();
            String query = "SELECT ProductID "
            + " FROM GiaoDich where TransID ='" + TransID + "' and SessionID = '" + SessionID + "'";

            connSql = dt.connect();
            int ProducID = (int)dt.executeScalar(query);

            return ProducID;
        }
        catch 
        {

            return -1;
        }

    }


    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        DataTable dt = loaddb();

        //GridView1.DataBind();
        GridView1.DataSource = dt;

        GridView1.DataBind();
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = loadalldb();
        if (dt.Rows.Count == 0)
        {
            Response.Write("<script>alert('Không có giao dịch nào đang vận chuyển')</script>");
            Response.Redirect("~/Admin/XemDSGD.aspx");
            
        }
        else
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

    }

    public DataTable loadalldb()
    {
        DataProvider dt = new DataProvider();
        connSql = dt.connect();
        SqlDataAdapter daDepart = null;
        daDepart = new SqlDataAdapter("Select * from CTGiaoDich where State= 0 ", connSql);
        DataSet ds = new DataSet();
        daDepart.Fill(ds);
        return ds.Tables[0];
    }

}